<template>
  <div class="cart-container">
    <el-table
      ref="cartTable"
      :data="$store.state.cartItems"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-if="$store.state.cartCount != 0"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="商品名称">
        <template slot-scope="scope">
          <img
            :src="scope.row.itemSwiperImgUrl[0].url"
            width="80"
            height="80"
          />
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column prop="discountPrice" label="单价" width="150">
        <template slot-scope="scope">
          {{ scope.row.discountPrice }}元
        </template>
      </el-table-column>
      <el-table-column label="数量" width="210">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.count"
            @change="handleChange"
            :min="1"
            :max="10"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="小计" width="150">
        <template slot-scope="scope">
          {{ scope.row.discountPrice * scope.row.count }}元
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            circle
            icon="el-icon-delete"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="cart-pay-box" v-if="$store.state.cartCount != 0">
      <div class="pay-detail">
        <p class="selected-count">
          已选择
          <span>{{ cartMultipleSelection.length }}</span>
          件
        </p>
        <p class="selected-total-price">
          合计:
          <span>{{ getSelectedAllPrice }}</span>
          元
        </p>
      </div>
      <div class="pay-btn-box">
        <el-button
          class="pay-btn"
          type="warning"
          :disabled="this.cartMultipleSelection.length == 0"
          @click="dialogCheckoutVisible = true"
          >去结算</el-button
        >
      </div>
    </div>

    <el-dialog width="30%" center :visible.sync="dialogPayTipsVisible">
      <el-result
        icon="success"
        title="订单提交成功!去付款咯～"
        subTitle="请在24小时内完成支付, 超时后将取消订单"
      >
        <template slot="extra">
          <el-button
            type="primary"
            size="medium"
            @click="changeOrderListActiveName('second')"
            >前往支付</el-button
          >
        </template>
      </el-result>
    </el-dialog>

    <!-- 检查支付信息弹窗 -->
    <el-dialog
      title="确认订单"
      :visible.sync="dialogCheckoutVisible"
      :before-close="handleClose"
      width="50%"
      center
    >
      <div class="checkout-address">
        <h2 class="checkout-title">收货地址</h2>
        <el-select
          class="address-selection"
          v-model="value"
          clearable
          placeholder="请选择"
          no-data-text="收货地址为空"
        >
          <el-option
            v-for="item in $store.state.userShippingAddress"
            :key="item.addressId"
            :label="item.address + item.detailAddress"
            :value="item.addressId"
          >
          </el-option>
        </el-select>
        <el-button
          class="checkout-add-address"
          type="primary"
          plain
          @click="dialogAddNewAddressFormVisible = true"
        >
          添加新地址
        </el-button>
      </div>
      <div class="checkout-items">
        <h2 class="checkout-title">商品</h2>
        <div
          class="checkout-items-box"
          v-for="item in cartMultipleSelection"
          :key="item.addressId"
        >
          <div class="checkout-item">
            <div class="checkout-item-detail">
              <img
                width="40"
                height="40"
                :src="item.itemSwiperImgUrl[0].url"
                alt=""
              />
              <p class="checkout-item-title">{{ item.title }}</p>
            </div>
            <p class="checkout-item-price">
              {{ item.discountPrice }}元 x {{ item.count }}
            </p>
            <p class="checkout-item-subtotal">
              {{ item.discountPrice * item.count }}元
            </p>
          </div>
          <el-divider class="checkout-items-box-divider"></el-divider>
        </div>
      </div>
      <div class="checkout-delivery-method">
        <h2 class="checkout-title">配送方式</h2>
        <p class="delivery-method">包邮</p>
      </div>
      <el-divider></el-divider>
      <div class="count-detail">
        <div>
          <p>商品件数:</p>
          <span>{{ cartMultipleSelection.length }} 件</span>
        </div>
        <div>
          <p>商品总价:</p>
          <span>{{ getSelectedAllPrice }} 元</span>
        </div>
        <div class="count-detail-important-box">
          <p>应付总额:</p>
          <span class="count-detail-important"
            >{{ getSelectedAllPrice }} 元</span
          >
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckoutVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrder"> 去结算 </el-button>
      </div>
    </el-dialog>

    <!-- 添加新地址弹窗 -->
    <el-dialog
      title="添加收货地址"
      center
      width="30%"
      :visible.sync="dialogAddNewAddressFormVisible"
      :before-close="handleClose"
      @closed="clearFormCache"
    >
      <el-form
        :model="newAddressForm"
        ref="newAddressForm"
        size="medium"
        label-position="left"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newAddressForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="newAddressForm.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="newAddressForm.address"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input
            type="textarea"
            autosize
            v-model="newAddressForm.detailAddress"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input
            v-model="newAddressForm.tag"
            autocomplete="off"
            placeholder="如“家”、“学校”。限五个字内"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddNewAddressFormVisible = false"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitNewAddressForm('newAddressForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <el-empty
      description="购物车里面空空如也~"
      v-if="$store.state.cartCount == 0"
    ></el-empty>
  </div>
</template>

<script>
export default {
  name: "CartContainer",
  data() {
    return {
      userOrderList: {
        orderListId: "",
        status: "",
        totalPrice: "",
        items: [],
        time: "",
      },
      dialogCheckoutVisible: false,
      dialogPayTipsVisible: false,
      cartMultipleSelection: [],
      value: "",
      dialogAddNewAddressFormVisible: false,
      newAddressForm: {
        addressId: "",
        name: "",
        phone: "",
        address: "",
        detailAddress: "",
        tag: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入名字", trigger: "blur" },
          { min: 1, max: 15, message: "长度在1到12个字内", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入正确的手机号", trigger: "blur" },
        ],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        tag: [{ max: 5, message: "长度限制在5个字内", trigger: "blur" }],
        select: [
          { required: true, message: "请选择收货地址", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    changeOrderListActiveName(newActiveName) {
      this.$router.push("/user/orderList");
      this.$store.commit("changeOrderListActiveName", newActiveName);
    },
    handleSelectionChange(val) {
      // console.log(val);
      this.cartMultipleSelection = val;
    },
    handleDelete(index, row) {
      // console.log(index, row);
      // 执行删除操作弹出确认框
      this.$confirm("确认删除所选商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 确认后进行的操作
          this.$store.commit("handleDeleteCartItem", index);
        })
        .catch(() => {
          // 取消后进行的操作
        });
    },
    handleChange(value) {
      // console.log(value);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    submitNewAddressForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const TSSUSA = this.$store.state.userShippingAddress.length;
          // console.log(TSSUSA == 0);
          this.newAddressForm.addressId =
            TSSUSA == 0
              ? 1
              : this.$store.state.userShippingAddress[0].addressId + 1;
          // 坑 如果不使用 Object.assign({}, this.newAddressForm) address将会被绑到与this.form一样的引用地址，修改this.form也等于修改address
          const address = Object.assign({}, this.newAddressForm);
          // console.log(address);
          this.$store.commit("handleAddNewAddress", address);
          this.dialogAddNewAddressFormVisible = false;
          this.$message({
            message: "添加地址成功",
            type: "success",
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitOrder() {
      if (this.value == "") {
        this.$message.error("请选择收货地址");
      } else {
        const TSSUOL = this.$store.state.userOrderList.length;
        this.userOrderList.orderListId =
          TSSUOL == 0
            ? 1000001
            : this.$store.state.userOrderList[0].orderListId + 1;
        this.userOrderList.status = "待支付";
        this.userOrderList.items = this.cartMultipleSelection;
        this.userOrderList.totalPrice = this.cartMultipleSelection
          .filter(function (n) {
            return n;
          })
          .reduce(function (pre, n) {
            return pre + n.discountPrice * n.count;
          }, 0);
        this.userOrderList.time = new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", " ");
        // console.log(this.userOrderList);
        const newOrderList = Object.assign({}, this.userOrderList);
        this.$store.commit("addNewOrderList", newOrderList);
        this.userOrderList.items.forEach((n) => {
          this.$store.commit("handleDeleteCartItemByItemId", n.itemId);
        });
        this.dialogCheckoutVisible = false;
        this.dialogPayTipsVisible = true;
      }
    },
    clearFormCache() {
      setTimeout(() => {
        // 清空newAddressForm
        this.newAddressForm.addressId = "";
        this.newAddressForm.name = "";
        this.newAddressForm.phone = "";
        this.newAddressForm.address = "";
        this.newAddressForm.detailAddress = "";
        this.newAddressForm.tag = "";
      }, 500);
    },
  },
  computed: {
    getSelectedAllPrice() {
      if (this.cartMultipleSelection.length == 0) {
        return 0;
      } else {
        return this.cartMultipleSelection
          .filter(function (n) {
            return n;
          })
          .reduce(function (pre, n) {
            return pre + n.discountPrice * n.count;
          }, 0);
      }
    },
  },
};
</script>

<style scoped>
.cart-container {
  background-color: #fff;
}

.cart-pay-box {
  height: 50px;
  margin-top: 20px;
  display: flex;
}

.pay-detail {
  flex: 8;
}
.selected-count {
  margin-left: 50px;
  float: left;
  line-height: 50px;
  font-size: 14px;
}
.selected-count span {
  color: #f00;
}
.selected-total-price {
  margin-right: 50px;
  float: right;
  line-height: 50px;
  font-size: 14px;
  color: #f00;
}
.selected-total-price span {
  font-size: 22px;
}

.pay-btn-box {
  flex: 2;
}
.pay-btn {
  height: 50px;
  width: 100%;
  border-radius: 0;
}

.checkout-address {
  margin-bottom: 30px;
}
.checkout-title {
  color: #333;
  font-size: 18px;
  line-height: 20px;
  margin-bottom: 10px;
}
/* .address-selection-form {
  display: inline-block;
  width: 300px;
  height: 40px;
} */
.address-selection {
  width: 300px;
}
.checkout-add-address {
  margin-left: 10px;
}

.checkout-item {
  display: flex;
  align-items: center;
}
.checkout-item-detail {
  flex: 6;
  display: flex;
  align-items: center;
}
.checkout-item-title {
  margin-left: 10px;
}
.checkout-item-price {
  flex: 2;
}
.checkout-item-subtotal {
  flex: 2;
}
.checkout-items-box-divider {
  margin: 13px 0;
}

.checkout-delivery-method {
  margin-top: 24px;
  display: flex;
  align-items: center;
}
.checkout-delivery-method .checkout-title {
  margin-bottom: 0;
}
.delivery-method {
  margin-left: 30px;
  color: #409eff;
}

.count-detail {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.count-detail div {
  width: 180px;
  padding: 5px 0;
  display: flex;
}
.count-detail div p {
  flex: 3;
}
.count-detail div span {
  flex: 4;
  color: #409eff;
  display: flex;
  justify-content: flex-end;
}
.count-detail-important-box {
  line-height: 22px;
}
.count-detail-important {
  font-size: 22px;
}
</style>